package com.rpc.center.event.listener;

import com.rpc.center.entity.ConsumerNode;
import com.rpc.center.entity.PublisherNode;
import com.rpc.center.event.eventtype.EventType;
import com.rpc.center.event.eventtype.OfflineEvent;
import com.rpc.center.manager.RPCServiceManager;
import com.rpc.common.entity.HostInfoPair;
import com.rpc.common.entity.response.PublisherOfflineRS;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OfflineListener extends EventListener<OfflineEvent> {
    @Autowired
    private RPCServiceManager manager;
    @Override
    public void actionListener(OfflineEvent event) {
        PublisherNode publisherNode=event.getPublisherNode();
        String serviceID=publisherNode.getServiceID();
        List<ConsumerNode> consumerNodeList=manager.getSubscriberList(serviceID);
        PublisherOfflineRS offlineRS=new PublisherOfflineRS();
        offlineRS.setAddress(publisherNode.getAddress());
        offlineRS.setPort(publisherNode.getPort());
        for(ConsumerNode node:consumerNodeList){
            //通知每个服务消费方，此服务发布方节点下线
            Channel channel=node.getChannel();
            channel.writeAndFlush(offlineRS);
        }
    }

    public OfflineListener() {
        this.setEventType(EventType.OFFLINE_EVENT);
    }
}
